let app = getApp();
// 引入SDK核心类
var QQMapWX = require('../../../libs/qqmap-wx-jssdk.min.js');
// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: 'I3SBZ-GHFKW-5XQRC-O76K3-VJP23-RNBM5' // 必填
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 列表数据
    addressList: [],
    contactName: null,
    contactPhone: null,
    address: null,
    buildingNature: null,
    propertyNature: null,
    businessAddressPonit: [],
    businessAddressName: []
  },
  add() {
    wx.navigateTo({
      url: '/pages/yuding/dizhi/add/add',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    that.setData({
      userInfo: wx.getStorageSync("userInfo"),
      businessAddressPonit: app.globalData.businessAddressPonit,
      businessAddressName: app.globalData.businessAddressName
    });
    wx.request({
      url: app.globalData.baseUrl + "/user/address/queryById",
      header: {
        "cookie": "JESSIONID=" + that.data.userInfo.sessionId
      },
      method: "GET",
      data: {
        userId: that.data.userInfo.userId
      },
      success(res) {
        console.log("getaddressRes", res);
        if (res.data == "请先登录") {
          wx.showToast({
            title: res.data,
            icon: "none",
            duration: 1500,
            success: function() {
              wx.switchTab({
                url: '/pages/huiyuan/huiyuan'
              });
            }
          });
        } else {
          that.setData({
            addressList: res.data
          });
        }
      },
      fail(err) {
        console.log("getaddressErr", err);
      }
    })
    
  },
  btn_delete: function(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.baseUrl + "/user/address/deleteById?id=" + id,
      header: {
        "cookie": "JESSIONID=" + that.data.userInfo.sessionId
      },
      method: "DELETE",
      success(res) {
        if (res.statusCode === 204) {
          wx.showToast({
            title: '删除成功！',
            icon: "success",
            duration: 1500,
            success() {
              wx.redirectTo({
                url: "/pages/yuding/dizhi/dizhi"
              });
            }
          })
        } else {
          wx.showToast({
            title: '服务器异常！',
            icon: "loading",
            duration: 1500
          });
        }
      },
      fail(err) {
        wx.showToast({
          title: '服务器异常！',
          icon: "loading",
          duration: 1500
        });
        console.log("deleteErr", err);
      }
    });
  },
  // 默认选中  单击事件
  select: function(res) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否选择当前地址?',
      success(click_res) {
        if(click_res.confirm) {
          var list = that.data.addressList;
          var index = res.currentTarget.dataset.index;
          list[index].selected = !list[index].selected;
          var contactName = list[index].contactName;
          var contactPhone = list[index].contactPhone;
          var address = list[index].address;
          var buildingNature = list[index].buildingNature;
          var propertyNature = list[index].propertyNature;
          var latitude = list[index].latitude;
          var longitude = list[index].longitude;
          for (var i = 0; i < list.length; i++) {
            if (i != index) {
              list[i].selected = false;
            } else {
              list[i].selected = true;
            }
          }
          let addressInfo = {
            contactName: contactName,
            contactPhone: contactPhone,
            address: address,
            buildingNature: buildingNature,
            propertyNature: propertyNature,
            latitude: latitude,
            longitude: longitude
          }
          wx.setStorage({
            key: 'addressInfo',
            data: addressInfo,
            success() {
              wx.navigateBack({
                url: '/pages/yuding/yuding'
              })
            }
          });
          wx.showLoading({
            title: '计算最近配送点',
          });
          let distributionPoint = that.data.businessAddressName[0];
          qqmapsdk.calculateDistance({
            mode: "driving",
            //from参数不填默认当前地址
            //获取表单提交的经纬度并设置from和to参数（示例为string格式）
            from: {
              latitude: addressInfo.latitude,
              longitude: addressInfo.longitude
            }, 
            to: that.data.businessAddressPonit, //终点坐标
            success: function (dis_res) {//成功后的回调
              wx.hideLoading();
              var res = dis_res.result;
              let dis = res.elements[0].distance;
              res.elements.forEach((val,index)=>{
                if(dis>val.distance) {
                  dis = val.distance
                  distributionPoint = that.data.businessAddressName[index];
                }
              });
              wx.setStorage({
                key: "dis",
                data: dis/1000,
              });
              wx.setStorage({
                key: 'distributionPoint',
                data: distributionPoint,
              })
            },
            fail: function (dis_error) {
              wx.hideLoading();
              wx.showToast({
                title: '微信服务异常！',
                icon: "loading",
                duration: 1500
              })
              console.error(dis_error);
            }
          });
        } else if (click_res.cancel) {
          return;
        }
      }
    })


  },
  btn_sub: function() {
    wx.redirectTo({
      url: '../new_receiving_address/new_receiving_address',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})